#include <stdint.h>
#include <ctl_api.h>
#include <LPC11xx.h>
#include "bluehand.h"

#define ADC_TIMEVAL (1000*10)
static uint16_t adval;
static uint32_t adc_ticks;

/*
 * Battery level indication
 *
 * 3.3 .. 3.5 --> 0
 * 3.5 .. 3.7 --> 1
 * 3.7 .. 4.0 --> 2
 * 4.0 .. 4.2 --> 3
 */
#define	THRES35	543   // 3500mv/2/(3300mv/1024) = 543
#define	THRES37	573
#define	THRES40	620

void adc_init()
{
  LPC_IOCON->R_PIO1_2 &= ~0x9f;	/* Reset FUNC, MODE and ADMODE bits */
  LPC_IOCON->R_PIO1_2 |= 0x02;	/* Selects function AD3 and ADMODE */

  LPC_SYSCON->SYSAHBCLKCTRL |= (1<< 13);	// Enable ADC clock
  LPC_SYSCON->PDRUNCFG &= ~(1<<4);		// Turn on ADC power

  LPC_ADC->CR = (2 << 8) | (1 << 3);
  LPC_ADC->INTEN = (1<<3);      // Enable AD3 interrupt
  ctl_unmask_isr(ADC_IRQn);
  LPC_ADC->CR |= (1<<24);       // Start next conversion
}

void adc_timer()
{
  uint16_t adval;

  if (++adc_ticks >= ADC_TIMEVAL) {
    adc_ticks = 0;
    LPC_ADC->CR |= (1<<24);       // Start next conversion
  }
}

void ADC_IRQHandler()
{
  ctl_enter_isr();
  if (LPC_ADC->STAT & (1<<3)) {
    adval = (LPC_ADC->DR[3] >> 6) & 0x3ff;
    LPC_ADC->CR &= ~(1<<24);       // clear start
    ctl_byte_queue_post_nb(&bq_event, EV_ADC_TIMER);
  }
  ctl_exit_isr();
}

void adc_icon_update()
{
  if (adval < THRES35)
    lcd_show_icon(ICON_BAT0);
  else if (adval < THRES37)
    lcd_show_icon(ICON_BAT1);
  else if (adval < THRES40)
    lcd_show_icon(ICON_BAT2);
  else
    lcd_show_icon(ICON_BAT3);
}
